<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-input
          v-model="dataForm.campusName"
          placeholder="校区名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="selectedOptions">
        <el-cascader
          v-model="selectedOptions"
          size="large"
          :options="options"
          :props="{ expandTrigger: 'hover', checkStrictly: false }"
          @change="handleCityChange"
          placeholder="请选择省市区"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="dataList"
      stripe
      v-loading="dataListLoading"
      style="width: 100%"
    >
      <el-table-column prop="campusId" label="校区id" width="180">
      </el-table-column>
      <el-table-column prop="campusName" label="校区名称" width="180">
      </el-table-column>
      <el-table-column prop="name" label="校区负责人"> </el-table-column>
      <el-table-column prop="num" label="校区总人数"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.campusId)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.campusId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <!-- 新增框 -->
    <el-dialog
      :title="!campusForm.campusId ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >
      <el-form
        :model="campusForm"
        :rules="dataRule"
        ref="campusForm"
        @keyup.enter.native="campusFormSubmit()"
        label-width="80px"
      >
        <el-form-item label="省市区" prop="city">
          <el-cascader
            size="large"
            :options="options"
            v-model="campusForm.city"
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="校区名称" prop="campusName">
          <el-input
            v-model="campusForm.campusName"
            placeholder="请输入校区名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="校区负责人" prop="userId">
          <el-select v-model="campusForm.userId" placeholder="请选择校区负责人">
            <el-option
              v-for="xqfzr in xqfzrList"
              :key="xqfzr.userId"
              :label="xqfzr.username"
              :value="xqfzr.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="campusFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { regionData } from "element-china-area-data";

export default {
  data() {
    return {
      options: regionData,
      selectedOptions: [],
      visible: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataForm: {
        campusName: "",
      },
      campusForm: {
        campusId: null,
        campusName: "",
        name: "",
        city: [],
      },
      xqfzrList: [],
      dataRule: {
        campusName: [
          { required: true, message: "校区名称不能为空", trigger: "blur" },
        ],
        city: [{ required: true, message: "省市区不能为空", trigger: "blur" }],
        userId: [
          { required: true, message: "校区负责人不能为空", trigger: "blur" },
        ],
      },
    };
  },
  components: {},
  activated() {
    this.getDataList();
    this.getXzfzr();
  },
  methods: {
    handleChange(value) {
      console.log(value);
    },
    // 获取校区分页数据
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/sf/campus/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          campusName: this.dataForm.campusName,
        }),
      }).then(({ data }) => {
        console.log(data);
        if (data && data.code === 0) {
          this.dataList = data.campusPage.records;
          this.totalPage = data.campusPage.total;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 获取未分配的校区负责人
    getXzfzr() {
      this.$http({
        url: this.$http.adornUrl("/sf/campus/getXqfzr"),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          this.xqfzrList = data.xqfzrList;
        } else {
          this.xqfzrList = [];
        }
      });
    },
    // 表单提交
    campusFormSubmit() {
      // 表单验证
      this.$refs["campusForm"].validate((valid) => {
        if (valid) {
          console.log(this.campusForm);
          this.$http({
            url: this.$http.adornUrl(
              `/sf/campus/${!this.campusForm.campusId ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData(
              {
                campusName: this.campusForm.campusName,
                campusId: this.campusForm.campusId,
                userId: this.campusForm.userId,
                city: this.campusForm.city,
              },
              false
            ),
          }).then(({ data }) => {
            console.log(data);
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 新增或修改
    addOrUpdateHandle(campusId) {
      // 重置表单
      this.$nextTick(() => {
        this.$refs["campusForm"].resetFields();
      });
      // 清空之前的数据尤其是campusId
      //this.campusForm = {};
      this.visible = true;
      // 如果修改就回显
      if (campusId != null) {
        this.$http({
          url: this.$http.adornUrl(`/sf/campus/info/${campusId}`),
          method: "get",
        }).then(({ data }) => {
          if (data && data.code === 0) {
            console.log(data);
            this.campusForm = data.campus;
          } else {
            this.campusForm = {};
          }
        });
      }
    },
    // 删除
    deleteHandle(campusId) {
      this.$confirm(`确定对[校区id=${campusId}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/campus/delete"),
            method: "post",
            data: this.$http.adornData([campusId], false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 点击城市事件
    handleCityChange(value) {
      console.log(this.selectedOptions);
      let len = value.length;
      // 如果长度为0 说明清空了城市条件，如果不为就提取城市的信息id
      if (len == 0) {
        this.getDataList();
      } else {
        this.dataListLoading = true;
        this.$http({
          url: this.$http.adornUrl("/sf/campus/list"),
          method: "get",
          params: this.$http.adornParams({
            page: this.pageIndex,
            limit: this.pageSize,
            campusName: this.dataForm.campusName,
            pcaid: this.selectedOptions[2],
          }),
        }).then(({ data }) => {
          console.log(data);
          if (data && data.code === 0) {
            this.dataList = data.campusPage.records;
            this.totalPage = data.campusPage.total;
          } else {
            this.dataList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
        });
      }
    },
  },
};
</script>